<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Springboot + WebSocket Demo</title>
</head>
<body>
<div>默认用户userId: xiaoming002</div>

<br>
<input type="text" id="text"/>
<input type="text" placeholder="请输入接收人userId" id="sendUserId" />
<button onclick="send()">发送消息</button>

<br>
<button onclick="closeWebSocket()">关闭WebSocket连接</button>

<div id="message"></div>
</body>
<script>
    var websocket = null, userId = "xiaoming002";

    if( 'WebSocket' in window ) {
        websocket = new WebSocket("ws://127.0.0.1:12306/websocket/" + userId)
    } else {
        alert("当前浏览器不支持WebSocket");
    }


    function setMessageInnerHtml(message) {
        document.getElementById("message").innerHTML += message + '<br/>'
    }

    function closeWebSocket() {
        websocket.close();
    }

    function send() {
        var message = document.getElementById('text').value;//要发送的消息内容

        if (message == "") {
            alert("发送信息不能为空！")
            return;
        } //获取发送人用户id
        var sendUserId = document.getElementById('sendUserId').value;
        if (sendUserId == "") {
            alert("发送人用户id不能为空！")
            return;
        }

        document.getElementById('message').innerHTML += ("我给" + sendUserId + "发送消息,消息内容为---->>" + message + '<br/>');
        message = message + "," + sendUserId//将要发送的信息和内容拼起来，以便于服务端知道消息要发给谁
        websocket.send(message);
    }

    window.onbeforeunload = function (ev) {
        closeWebSocket();
    }

    websocket.onerror = function (ev) {
        showMessage('连接错误', ev, '连接错误');
    }

    websocket.onopen = function (ev) {
        showMessage('连接成功', ev, '连接成功');
    }

    websocket.onmessage = function (ev) {
        showMessage('收到消息回调', ev, ev.data);
    }

    websocket.onclose = function (ev) {
        showMessage('连接关闭', ev, '连接关闭');
    }

    function showMessage(title, ev, message) {

        console.info(title, ev);
        setMessageInnerHtml(message);
    }
</script>
</html>